'use strict'

const sha1 = require('sha1')
const Promise = require('bluebird')
const request = Promise.promisify(require('request'))

const prefix = 'https://api.weixin.qq.com/cgi-bin/'
const api = {
    accessToken:prefix + 'token?grant_type=client_credential'
}


function Wechat(opts) {
    var that = this
    this.appId = opts.appId
    this.appSecret = opts.appSecret
    this.getAccessToken = opts.getAccessToken
    this.saveAccessToken = opts.saveAccessToken

    this.getAccessToken().then(function (data) {
        try {
            data = JSON.parse(data)
        }catch (e){
            return that.updateAccessToken()
        }
        if(that.isValidAccessToken(data)){
            //Promise.resolve(data)
            return data
        }else{
            return that.updateAccessToken()
        }
    }).then(function (data) {
        that.access_token = data.access_token
        that.expires_in = data.expires_in

        that.saveAccessToken(data)

    })
}

Wechat.prototype.updateAccessToken = function () {
    const appId = this.appId
    const appSecret = this.appSecret
    var url = api.accessToken + '&appid=' + appId + '&secret=' + appSecret

    return new Promise(function (resolve,reject) {
        request({url:url,json:true}).then(function (response) {
            const data = response.body
            const now = (new Date().getTime())
            console.log(data)
            if (!data.expires_in){
                reject('数据有问题')
            }
            var expires_in = now + (data.expires_in - 20)*1000
            data.expires_in = expires_in

            resolve(data)
        })

    })

}

Wechat.prototype.isValidAccessToken = function (data) {
    if(!data || !data.access_token || !data.expires_in){
        return false
    }

    const access_token = data.access_token
    const expires_in = data.expires_in
    const now = (new Date().getTime())

    if (now < expires_in){
        return true
    }else{
        return false
    }
}

module.exports = Wechat